<?php
namespace app\common\model;

class Software extends Model
{
    const bit_datalist = [
        0 => '通用',
        32 => '32位(x86)',
        64 => '64位(x64)',
    ];

    const latest_datalist = [
        0 => '否',
        1 => '是',
    ];

    const discard_datalist = [
        0 => '否',
        1 => '是',
    ];

    protected $searchOptions = [
        'name'    => ['like', '%%%s%%'],// 软件名
        'version' => ['like', '%%%s%%'],// 版本号
        'bit'     => ['='],// 位数
        'type'    => ['='],// 类型（分类）
        'latest'  => ['='],// 是否最新
        'discard' => ['='],// 是否废弃
    ];

    /**
     * 获取器：大小文本
     * @param null $value
     * @param array $data
     * @return string
     */
    public function getSizeTextAttr($value, $data)
    {
        $size = $data['size'];
        $unit = null;
        foreach (['B', 'K', 'M'] as $item) {
            if (null !== $unit) {
                $size /= 1024;
            }

            $unit = $item;

            if ($size < 1024) break;
        }

        return round($size, 2) . $unit;
    }

    /**
     * 所属分类
     * @return \think\model\relation\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class, 'type', 'name')->field(['name', 'title']);
    }

    /**
     * 文章关联
     * @return \think\model\relation\HasManyThrough
     */
    public function article()
    {
        return $this->hasManyThrough(Article::class, Category::class, 'name', 'category_id', 'type', 'id');
    }
}